import { DaHuaICCBaseService } from "./base";
import { dahua } from "./type";
import * as crypto from "crypto";

/**
 * icc 鉴权服务
 */
export class AuthService extends DaHuaICCBaseService {
	/** 获取公钥 */
	async getPublicKey() {
		const url = `${this.config.baseUrl}/evo-apigw/evo-oauth/1.0.0/oauth/public-key`;
		const res = await this.curl<dahua.icc.IResponse<{ publicKey: string }>>(url, {
			method: "get",
			dataType: "json",
		});
		this.handleResponseException(res);
		const data = res.data.data.publicKey;
		return data;
	}

	/** 认证接口，获取token */
	async getAccessToken(publicKey: string) {
		const url = `${this.config.baseUrl}/evo-apigw/evo-oauth/1.0.0/oauth/extend/token`;
		const pkps = this.passwordEncrypt(this.config.password, publicKey);
		const params = {
			grant_type: "password",
			username: this.config.username,
			password: pkps.password,
			client_id: this.config.clientId,
			client_secret: this.config.clientSecret,
			public_key: publicKey,
		};

		const res = await this.curl<dahua.icc.IResponse<dahua.icc.AuthResponse>>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data: params,
		});

		this.handleResponseException(res, "获取token失败");
		return res.data.data;
	}

	/** 使用rsa公钥加密用户密码 */
	private passwordEncrypt(password: string, publicKey: string) {
		publicKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
		// const publicKeyBuffer = Buffer.from(publicKey, "base64");
		const passwordBuffer = Buffer.from(password, "utf8");

		const encrypted = crypto.publicEncrypt(
			{
				key: publicKey,
				padding: crypto.constants.RSA_PKCS1_PADDING,
			},
			passwordBuffer
		);
		return {
			password: encrypted.toString("base64"),
			publicKey,
		};
	}
}
